import AmapConfig from '@/config/amap'

// 高德地图工具类
class AmapUtils {
  constructor() {
    this.map = null;
    this.geocoder = null;
    this.key = AmapConfig.key;
    this.securityJsCode = AmapConfig.securityJsCode;
  }

  // 初始化地图
  initMap(containerId) {
    return new Promise((resolve, reject) => {
      if (window.AMap) {
        this.createMap(containerId, resolve);
      } else {
        window._AMapSecurityConfig = {
          securityJsCode: this.securityJsCode,
        };
        // 动态加载高德地图SDK
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = `https://webapi.amap.com/maps?v=2.0&key=${this.key}&plugin=AMap.Geocoder,AMap.PlaceSearch`;
        script.onload = () => {
          this.createMap(containerId, resolve);
        };
        script.onerror = reject;
        document.head.appendChild(script);
      }
    });
  }

  // 创建地图实例
  createMap(containerId, resolve) {
    try {
      this.map = new window.AMap.Map(containerId, {
        zoom: 15,
        mapStyle: 'amap://styles/normal'
      });
      // 初始化地理编码器
      this.geocoder = new window.AMap.Geocoder({
        radius: 1000,
        extensions: 'all'
      });
      // 初始化地点搜索
      this.placeSearch = new window.AMap.PlaceSearch({
        pageSize: 10,
        pageIndex: 1
      });

      resolve(this.map);
    } catch (error) {
      console.error('地图初始化失败:', error);
    }
  }

  // 根据名称查找GPS坐标
  async searchLocationByName(name) {
    return new Promise((resolve, reject) => {
      if (!this.placeSearch) {
        reject(new Error('地图未初始化'));
        return;
      }

      this.placeSearch.search(name, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          const pois = result.poiList.pois;
          if (pois && pois.length > 0) {
            const location = pois[0].location;
            resolve({
              lng: location.lng,
              lat: location.lat,
              name: pois[0].name,
              address: pois[0].address
            });
          } else {
            reject(new Error('未找到相关位置'));
          }
        } else {
          reject(new Error('搜索失败'));
        }
      });
    });
  }

  // 添加标记点
  addMarker(location, options = {}) {
    if (!this.map) return null;

    // 检查是否为emoji图标
    const isEmoji = options.icon && options.icon.length <= 2 && /[\u{1F600}-\u{1F64F}]|[\u{1F300}-\u{1F5FF}]|[\u{1F680}-\u{1F6FF}]|[\u{1F1E0}-\u{1F1FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/u.test(options.icon);

    if (isEmoji) {
      // 使用自定义HTML标记显示emoji
      const marker = new window.AMap.Marker({
        position: [location.lng, location.lat],
        title: options.title || location.name,
        content: `<div style="
          font-size: 24px; 
          text-align: center; 
          line-height: 1; 
          background: white; 
          border-radius: 50%; 
          width: 32px; 
          height: 32px; 
          display: flex; 
          align-items: center; 
          justify-content: center;
          box-shadow: 0 2px 8px rgba(0,0,0,0.2);
          border: 2px solid #fff;
        ">${options.icon}</div>`,
        offset: new window.AMap.Pixel(-16, -16),
        ...options
      });
      marker.setMap(this.map);
      return marker;
    } else {
      // 使用默认图标
      const marker = new window.AMap.Marker({
        position: [location.lng, location.lat],
        title: options.title || location.name,
        icon: options.icon || 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
        ...options
      });
      marker.setMap(this.map);
      return marker;
    }
  }

  // 设置地图中心
  setCenter(lng, lat) {
    if (this.map) {
      this.map.setCenter([lng, lat]);
    }
  }

  // 设置缩放级别
  setZoom(zoom) {
    if (this.map) {
      this.map.setZoom(zoom);
    }
  }

  // 清除所有标记
  clearMarkers() {
    if (this.map) {
      this.map.clearMap();
    }
  }
}

export default new AmapUtils();
